package com.allwe.client.simple;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * kafka生产者配置
 *
 * @Author: AllWe
 * @Date: 2024/09/24/17:57
 */
@Slf4j
public class HelloKafkaConsumer {
    public static void main(String[] args) {
        // 设置属性
        Properties properties = new Properties();
        // 指定连接的kafka服务器地址，多台就用“,”隔开，如果某一台宕机生产者依然可以连接
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "39.107.66.31:9092");
        // 设置key和value的序列化器，使java对象转换成二进制数组
        properties.put("key.deserializer", StringDeserializer.class);
        properties.put("value.deserializer", StringDeserializer.class);
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");

        // new一个消费者consumer
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
        try {
            // 订阅哪些主题，可以多个，推荐订阅一个主题
            consumer.subscribe(Collections.singleton("topic_1"));
            // 死循环里面实现监听
            while (true) {
                // 每间隔1s，取一次消息，可能取到多条消息
                // 设置一秒的超时时间
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println("key:" + record.key() + ",value:" + record.value());
                }
            }
        } finally {
            // 释放连接
            consumer.close();
        }
    }
}
